from pivelli.options import o as options

class HttpException(Exception):
	pass

def request(url, addr=options.gateway, src_ip=options.bind_ip):
	import socket, IN
	s = socket.socket()
	s.bind((src_ip, 0),)
	msg = 'GET %s HTTP/1.1\r\nHost: %s\nConnection: close\r\n\r\n' % (url, options.gateway)
	s.connect((addr, 80),)
	sent_bytes = 0
	while sent_bytes < len(msg):
		sent_bytes += s.send(msg[sent_bytes:])
	data = s.recv(4096)
	s.close()
	try:
		h, b = data.split('\r\n\r\n')
		return h, b
	except ValueError:
		raise HttpException, 'Cannot parse response body'

def xmlrequest(*args, **kwargs):
	import xmltramp
	headers, body = request(*args, **kwargs)
	header_lines = headers.split('\n')
	first_line = header_lines[0].split()
	if first_line[1] == '200':
		r = xmltramp.parse(body)
		return xmltramp.Namespace(r._name[0]), r
	else:
		raise HttpException(headers.split('\n')[0])
